package api;

import cn.hutool.json.JSONUtil;
import comment.ApplicationVariable;
import lombok.SneakyThrows;
import model.Dish;
import model.Order;
import model.ResultData;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/orderdetail")
public class OrderDetailServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer oid = Integer.parseInt(req.getParameter("oid"));
        int state = -1;
        String msg = "未知错误";
        List<Dish> data = new ArrayList<>();

        if(oid != null && oid > 0){
            //参数有效
            Connection connection = DBUtil.getConnection();
            String sql = "select * from dish where did in(select did from orderdeatil where oid=?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1,oid);
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()){
                Dish dish = new Dish();
                dish.setName(resultSet.getString("name"));
                dish.setPrice(resultSet.getBigDecimal("price"));
                data.add(dish);
            }
        }
        else {
            //参数无效
            msg = "参数无效";
        }

        resp.setContentType(ApplicationVariable.APPLICATION_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(new ResultData(state,data,msg)));
    }
}
